/*
 * Copyright © 2022-now 尛飛俠（Denvie） All rights reserved.
 */

package cn.denvie.springcloud.seata.auth.service;

import cn.denvie.springcloud.seata.auth.feign.AccountFeignService;
import cn.denvie.springcloud.seata.auth.model.vo.AccountDetails;
import cn.denvie.springcloud.seata.common.model.entity.Account;
import cn.denvie.springcloud.seata.common.model.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * AuthUserDetailsService。
 *
 * @author Denvie
 * @date 2022/4/18
 * @since 1.0.0
 */
@Slf4j
@Component
public class AuthUserDetailsService implements UserDetailsService {
    @Autowired
    private AccountFeignService accountFeignService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("loadUserByUsername: {}", username);

        if (StringUtils.isEmpty(username)) {
            throw new RuntimeException("username can not be empty.");
        }

        ResultVo<Account> resultVo = accountFeignService.getByUserId(username);
        if (resultVo.getData() == null) {
            throw new UsernameNotFoundException("user: " + username + " not found.");
        }

        return new AccountDetails(resultVo.getData());
    }
}
